package smy.att;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import brut.androlib.Androlib;
import brut.androlib.AndrolibException;
import brut.androlib.res.util.ExtFile;

public class AndroidApplication {
	String manifest;
	public String path;

	public static AndroidApplication OpenApk(String APK_Path) {
		Androlib androlib = new Androlib();
		AndroidApplication result = new AndroidApplication();
		try {
			File temporaryPath = new File(APK_Path + "_dir");
			if (!temporaryPath.exists())
			{
				temporaryPath.mkdir();
			}
			// If there exists AndroidManifest.xml
			File manifestFile = new File(temporaryPath.getAbsolutePath() + "/AndroidManifest.xml");
			if (manifestFile.exists())
			{			
				result.manifest = Helper.ReadInputStream(new FileInputStream(manifestFile));
				result.path     = APK_Path;
				return result;
			}
			ExtFile apkFile = new ExtFile(APK_Path);
			androlib.decodeManifestFull(apkFile , temporaryPath , androlib.getResTable(apkFile, true));
			
			// Read the manifest
			result.manifest = Helper.ReadInputStream(new FileInputStream(manifestFile));
			result.path     = APK_Path;
			manifestFile.delete();
			return result;
		} catch (AndrolibException e) {
			throw new RuntimeException("Cannot Open APK File");
		} catch (FileNotFoundException e) {
			System.out.println(e.toString());
			throw new RuntimeException("Cannot Write Temporary File");
		} catch (IOException e) {
			throw new RuntimeException("Cannot Decode APK File");
		}
	}
	
	public String MainActivityName() {
		if (manifest == null)
		{
			throw new RuntimeException("Unexcepted Failure");
		}

		String[] activity_list = manifest.split("<activity");
		for (String activity : activity_list) 
		{
			if (activity.contains("intent-filter") && activity.contains("android.intent.action.MAIN"))
			{
				Pattern pattern = Pattern.compile("android:name=\"([^\"]*)\"");
				Matcher match   = pattern.matcher(activity);
				if (match.find()) 
				{
					return match.group(1);
				}
			}
		}
		return "";
	}
	
	public String PackageName() {
		if (manifest == null)
		{
			throw new RuntimeException("Unexcepted Failure");
		}
		
		Pattern pat = Pattern.compile("package=\"(.*)\"");
		Matcher matcher = pat.matcher(manifest);
		
		if (matcher.find())
		{
			return matcher.group(1);
		}
		return "";
	}
}
